package com.lijiayuedaren.dao;

import com.lijiayuedaren.entity.Image;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class ImgNameDao extends BaseDao {
    public void saveName(String name, int width, int height, double ratio, long size, Date lastModified) {
        try {
             template.update("INSERT INTO imgTrack VALUES(NULL,?,?,?,?,?,?,0,0)",name,width,height,ratio,size,lastModified);
        } catch (DataAccessException e) {
           e.printStackTrace();
        }
    }

    public List<Image> getImage(String type,int current,int size) {
//        String sql = "SELECT * FROM imgtrack  ORDER BY "+type+" DESC LIMIT "+((current-1)*size)+","+size+"";
        String sql = "SELECT * FROM imgtrack WHERE ratio>2 AND ratio<2.2 and hadseem = 0 ORDER BY width DESC ";
        return template.query(sql,new BeanPropertyRowMapper<>(Image.class));
    }

    public int getCount() {
        return template.queryForObject(" select  count(*) from imgtrack",int.class);
    }


    //根据id获取一组图片
    public List<Image> getImageById(String[] ids) {
        StringBuilder sql=new StringBuilder("select * from imgtrack where id in (");
        for (int i = 0; i < ids.length; i++) {
            if (i == ids.length - 1) {
                sql.append("?) and hadseem=0 and width > 500 and height > 500 order by ratio ");
            } else {
                sql.append("?,");
            }
        }
        return template.query(sql.toString(),new BeanPropertyRowMapper<>(Image.class),ids);
    }

    //根据id获取一张指定图片
    public String getOneImageName(int id) {
        return template.queryForObject("select name from imgtrack where id=?",String.class,id);
    }

    //根据id删除指定图片
    public void deleteImage(int id) {
        template.update("DELETE FROM imgtrack WHERE id=?",id);
    }

    //将删除的图片id和name保存到delected表
    public void saveDelete(String name,int id) {
        template.update("insert into delected values (null,?,?)",name,id);
    }

    //将提取过的图片存到hadSeem表
    public void hadSeeem(int id, String name) {
        template.update("INSERT INTO hadSeem VALUES (?,?)",id,name);
    }

    //将图片存到收藏表
    public void setFavorit(int id,String name) {
        template.update("INSERT INTO favoriteimg VALUES (?,?)",id,name);
    }

    //设置指定id的图片hadseem为1
    public void setHadSeem(String[] ids) {
        StringBuilder sql=new StringBuilder("UPDATE imgtrack SET hadseem=0 WHERE id IN (");
        for (int i = 0; i < ids.length; i++) {
            if (i == ids.length - 1) {
                sql.append("?)");
            } else {
                sql.append("?,");
            }
        }
        template.update(sql.toString(),ids);
    }
}
